var util = require('../../utils/util.js')
var app = getApp();
var md5 = require('../md5.js');
function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
function array2String(buffer) {
  let hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return `${hexArr[7]}:${hexArr[6]}:${hexArr[5]}:${hexArr[2]}:${hexArr[1]}:${hexArr[0]}`
}
function countdown(that) {
  var second = that.data.second
  if (second == 0) {
    that.setData({
      second: ""
    });
    return;
  }
  var time = setTimeout(function () {
    that.setData({
      second: second - 1
    });
    countdown(that);
  }
    , 1000)
}

function Uint8ArrayToString(fileData) {
  var dataString = "";
  for (var i = 0; i < fileData.length; i++) {
    dataString += String.fromCharCode(fileData[i]);
  }

  return dataString

}

function Utf8ArrayToStr(array) {
  var out, i, len, c;
  var char2, char3;

  out = "";
  len = array.length;
  i = 0;
  while (i < len) {
    c = array[i++];
    switch (c >> 4) {
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
        // 0xxxxxxx
        out += String.fromCharCode(c);
        break;
      case 12: case 13:
        // 110x xxxx 10xx xxxx
        char2 = array[i++];
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx 10xx xxxx 10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode(((c & 0x0F) << 12) |
          ((char2 & 0x3F) << 6) |
          ((char3 & 0x3F) << 0));
        break;
    }
  }

  return out;
}
function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint8Array(buf));
}
/**
*对象转换为Map
*/
function objToStrMap(obj) {
  let strMap = new Map();
  for (let k of Object.keys(obj)) {
    strMap.set(k, obj[k]);
  }
  return strMap;
}

Page({
  data: {
    second: 10,
    'cardtype':''
  },
  submit: function () {
    this.setData({
      showModal: true
    })
  },
  //底部导航跳转
  //底部导航跳转
  toAiIndex: function () {
    util.toAiIndex()
  },
  toContactsIng: function () {
    util.toContactsIng()
  },
  toProductRevision: function () {
    util.toProductRevision()
  },
  toMy: function () {
    util.toMy()
  },
  toBadge: function () {
    util.toBadge()
  },
  onLoad: function () {
   
      var str='D31125000101'
      var arr = [];
      for (var i = 0, j = str.length; i < j; ++i) {
        arr.push(str.charCodeAt(i));
      }

    var tmpUint8Array = new Uint8Array(arr);
    console.log('tmpUint8Array=' + tmpUint8Array) 
    
    countdown(this);
    //开启蓝牙设备
    var that = this;
    //68,51,49,49,50,53,48,48,48,49,48,49
    
    var un8 = new Uint8Array(10)
    un8[0] = 211
    un8[1] = 17
    un8[2] = 37
    un8[3] = 0
    un8[4] = 1
    un8[5] = 1
    un8[6] = 76
    un8[7] = 1
    un8[8] = 17
    un8[9] = 10
    
  //  var un8str = Utf8ArrayToStr(un8)
    var mm = ab2hex(un8)
    console.log('mm='+mm);
    wx.getSystemInfo({
      success: function(res) {
        console.log('platform:' + res.platform)//ios android
      },
    })
 //   var show;
  //  wx.scanCode({
  //    success: (res) => {
   //     this.show = "结果:" + res.result + "二维码类型:" + res.scanType + "字符集:" + res.charSet + "路径:" + res.path;
        
  //      console.log('result:' + res.result)
 //     },
  //    fail: (res) => {
      
  //    },
  //    complete: (res) => {
 //     }
 //   })
//return
    var resDeviceName = '';
    var resDeviceRssi = '';
    //设置语言0:中文，1：英文
    var setlanguage = wx.getStorageSync('setlanguage')
    if ((wx.getStorageSync('setlanguage') || !"".trim() == wx.getStorageSync('setlanguage'))) {
      this.setData({
        setlanguage: wx.getStorageSync('setlanguage')
      })
      if (setlanguage == 1) {
        wx.setNavigationBarTitle({
          title: 'Intelligent terminal interaction'
        })
      } else {
        wx.setNavigationBarTitle({
          title: '智能终端互动'
        })
      }
    } else {
      wx.setStorageSync('setlanguage', 0);
      this.setData({
        setlanguage: 0
      })
    }
    //判断蓝牙mac 不为null 或者''调用接口返回资料
    if (wx.openBluetoothAdapter) {
      wx.openBluetoothAdapter({
        success: function (res) {
          /* 获取本机的蓝牙状态 */
          setTimeout(() => {
            that.getBluetoothAdapterState()
          }, 1000)
        },
        fail: function (err) {
          // 初始化失败
        }
      })
    }
  },
  getBluetoothAdapterState() {
    var that = this;
    that.toastTitle = '检查蓝牙状态'
    wx.getBluetoothAdapterState({
      success: function (res) {
        console.log(JSON.stringify(res.errMsg) + "\n蓝牙是否可用：" + res.available);
        that.startBluetoothDevicesDiscovery()
      },
      fail(res) {
        console.log(res)
      }
    })
  },

  startBluetoothDevicesDiscovery() {
    var that = this;
    setTimeout(() => {
      wx.startBluetoothDevicesDiscovery({
        success: function (res) {
          console.log('搜索设备返回' + JSON.stringify(res))
          /* 获取蓝牙设备列表 */
          that.getBluetoothDevices()
        },
        fail(res) {
        }
      })
    }, 1000)
  },
  getBluetoothDevices() {
    var that = this;
    setTimeout(() => {
      wx.getBluetoothDevices({
        services: [],
        allowDuplicatesKey: false,
        interval: 0,
        success: function (res) {
          var curDeviceName = '';
          var curDeviceRssi = '';
          var curDeviceId = '';
          var advertisData ='';
          var serviceData='';
          console.log('deviceleg:' + res.devices.length)
          for (var i = 0; i < res.devices.length; i++) {
            if (res.devices[i].name == 'XT_PICO' || res.devices[i].name == 'Exhibit') { 
              //筛选信号强度最大的资料卡或者胸卡       
              if (curDeviceId!=''){
                if (curDeviceRssi < res.devices[i].RSSI){
                  curDeviceName = res.devices[i].name
                  curDeviceId = res.devices[i].deviceId
                  curDeviceRssi = res.devices[i].RSSI
                  advertisData = res.devices[i].advertisData
                  serviceData = res.devices[i].serviceData
                }
              }else{
                curDeviceName = res.devices[i].name
                curDeviceId = res.devices[i].deviceId
                curDeviceRssi = res.devices[i].RSSI
                advertisData = res.devices[i].advertisData
                serviceData = res.devices[i].serviceData
              }
            }
          }
          that.setData({
            'blename': curDeviceName,
            'bleid': curDeviceId
          });
     //     console.log('advertisData', advertisData)
       //00000200-0000-1000-8000-00805F9B34FB
      //   var m = new Map()
      //    m.set(1, 'abc')
       //   m.set('啊哈哈', 853)
     //     m.set(6, 123)
      //    m.set('00000200-0000-1000-8000-00805F9B34FB', '00')
       //   console.log(m)
     //     console.log(m.get('00000200-0000-1000-8000-00805F9B34FB'))
     //    var map = objToStrMap(serviceData)
     //     var strMap = new Map()
     //         strMap = serviceData
         //var kk = strMap.get(1)
      //    console.log('strMap=', strMap)
     //     for (let key in strMap){
    //         console.log('strMap1=', strMap[key].Object)
     //     }
        //  console.log('strMap1=', strMap.get(00000200-0000-1000-8000-00805F9B34FB))
         // for (let k of Object.keys(obj)) {
      //    console.log('map=', strMap)
    //      console.log('serviceData11' + JSON.stringify(serviceData) + "\n")
          
     //     console.log('serviceData', serviceData)
   //       console.log('ab2hex=', ab2hex(serviceData))
     //     var aa=''
         // for (var a = serviceData, i = new DataView(a), n = "", s = 0; s < i.byteLength; s++) {
          // n += String.fromCharCode(i.getUint8(s))
           //console.log('n', n)
        //}
        //  let arrayBuffer = arraybuf;
        //  let unit8Arr = new Uint8Array(arrayBuffer);
      //   console.log('aa=' + unit8Arr);
       //   let encodedString = String.fromCharCode.apply(null, unit8Arr)
        //  console.log('decodedString' + encodedString)
         // decodedString = decodeURIComponent(escape((encodedString)));//没有这一步中文会乱码
         // console.log(decodedString);
        // let unit8Arr = new unit8Arr(advertisData)
        //  let encodedString = String.fromCharCode.apply(null, unit8Arr)
         // decodeString = decodeURIComponent(escape(encodedString))
        //  console.log('advertisData', decodeString)
         // var buff = arraybuf.slice(0,10);
        //  var arrayBuff = Array.prototype.map.call(new Uint8Array(buff), x => ('00' + x.toString(16)).slice(-2)).join(':');
        //  var arrayMac = arrayBuff.toUpperCase();
       //   console.log('arrayMac:' + arrayMac)
          //处理curDeviceId
          var deviceIdArray = curDeviceId.split(':')
          var resDeviceId = ''
          for (var i = 0; i < deviceIdArray.length;i++){
            resDeviceId += deviceIdArray[i]
          }
          console.log('curDeviceId：' + resDeviceId)
          console.log('curDeviceRssi：' + curDeviceRssi)
          console.log('curDeviceName：' + curDeviceName)
          console.log('搜设备数目：' + res.devices.length)
          console.log('设备信息：\n' + JSON.stringify(res.devices) + "\n")
          res.devices.forEach(
            element=>{
              var device = element
              console.log(device);
            }
          );

          //调用pico接口获取资料id，或者名片id
          if (curDeviceId != '' && curDeviceName!=''){
            var exhibitionid = wx.getStorageSync('exhibitionid')
            var u = wx.getStorageSync('u')
            var timestamp = Date.parse(new Date());
            timestamp = timestamp / 1000;
            var cururl = app.globalData.picoaddress + '/attendee/ble/pickupinfo'
            var t = {}
            t["v"] = '1.0.0'
            t["client"] = 'ios'
            t["timestamp"] = timestamp
            t["lan"] = 'cn'
            t["bleid"] = resDeviceId
            t["blename"] = curDeviceName
            t["exhibitionid"] = exhibitionid
            t["u"] = u
            var sign = app.globalData.picotoken + 'bleid' + resDeviceId + 'blename' + curDeviceName + 'clientiosexhibitionid' + exhibitionid+'timestamp' + timestamp + app.globalData.picotoken
            console.log(sign)
            var curb64 = md5.zhMD5(sign)
            console.log(curb64)
            t["sign"] = curb64
            wx.request({
              header: {
                'content-type': 'application/x-www-form-urlencoded',
              },
              url: cururl,
              method: 'post',
              data: t,
              success(res) {
                var mesg = res.data
                console.log('mesg=' + mesg)
                var curdata = mesg.data
                var infoid = curdata.infoid
                var cardtype = curdata.cardtype+''
                //调用获取资料接口
                var timestamp = Date.parse(new Date());
                timestamp = timestamp / 1000;
                var cururl = app.globalData.picoaddress + '/attendee/materials/gainmaterials'
                var m = {}
                m["v"] = '1.0.0'
                m["client"] = 'ios'
                m["timestamp"] = timestamp
                m["lan"] = 'cn'
                m["exhibitionid"] = exhibitionid
                //联系人id
                m["u"] = u
                m["materialids"] = infoid
                var sign = app.globalData.picotoken + 'clientiosexhibitionid' + exhibitionid+'materialids' + infoid+'timestamp' + timestamp + app.globalData.picotoken
                console.log(sign)
                var curb64 = md5.zhMD5(sign)
                console.log(curb64)
                m["sign"] = curb64
                wx.request({
                  header: {
                    'content-type': 'application/x-www-form-urlencoded',
                  },
                  url: cururl,
                  method: 'post',
                  data: m,
                  success(res) {
                    //根据cardtype 判断页面 显示
                    console.log('cardtype:' + cardtype)
                    that.setData({
                      'cardtype': cardtype,
                    });
                    console.log('获取资料' + JSON.stringify(res))
                    wx.stopBluetoothDevicesDiscovery({
                      success: function (res) {
                        console.log("停止搜索" + JSON.stringify(res.errMsg));
                        that.setData({
                          info: "停止搜索" + JSON.stringify(res.errMsg),
                        })
                      }
                    })
                  }, fail: res => {
                    console.log(res, "error")
                  }
                })
                console.log('蓝牙返回' + JSON.stringify(res))
                console.log('infoid=', infoid)
              }, fail: res => {
                console.log(res, "error")
              }
        
           })
          }
        },
        fail(res) {
          console.log(res, '获取蓝牙设备列表失败=====')
        }
      })
    }, 2000)
  },
})